package com.yaolaizaixian.merchant.order;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.victor.loading.rotate.RotateLoading;
import com.yaolaizaixian.merchant.R;
import com.yaolaizaixian.merchant.adapter.OrderListAdapter;
import com.yaolaizaixian.merchant.base.BaseActivity;
import com.yaolaizaixian.merchant.base.BaseInfo;
import com.yaolaizaixian.merchant.base.BaseModel;
import com.yaolaizaixian.merchant.bean.OrderData;
import com.yaolaizaixian.merchant.bean.OrderList;
import com.yaolaizaixian.merchant.bean.OrderListModel;
import com.yaolaizaixian.merchant.home.ConfirmActivity;
import com.yaolaizaixian.merchant.home.OrderSuccessActivity;
import com.yaolaizaixian.merchant.home.SaoMaActivity;
import com.yaolaizaixian.merchant.utils.DateUtils;
import com.yaolaizaixian.merchant.utils.GsonUtil;
import com.yaolaizaixian.merchant.utils.MyNetUtils;
import com.yaolaizaixian.merchant.utils.MyUtils;
import com.yaolaizaixian.merchant.utils.SharedPreferencesUtil;
import com.yaolaizaixian.merchant.utils.Toasty;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/2/23.
 * 订单查询列表
 */
public class OrderListActivity extends BaseActivity {

    private static final String TAG = "OrderListActivity";
    @BindView(R.id.ll_back)
    AutoLinearLayout llBack;
    @BindView(R.id.tv_title_text)
    TextView tvTitleText;
    @BindView(R.id.ll_chathome_saoyissao)
    LinearLayout llChathomeSaoyissao;
    @BindView(R.id.ll_chathome_seach)
    LinearLayout llChathomeSeach;
    @BindView(R.id.tv_orderlist_all)
    TextView tvOrderlistAll;
    @BindView(R.id.iv_orderlist1)
    ImageView ivOrderlist1;
    @BindView(R.id.rl_orderlist_all)
    AutoRelativeLayout rlOrderlistAll;
    @BindView(R.id.tv_orderlist_bulu)
    TextView tvOrderlistBulu;
    @BindView(R.id.iv_orderlist2)
    ImageView ivOrderlist2;
    @BindView(R.id.rl_orderlist_bulu)
    AutoRelativeLayout rlOrderlistBulu;
    @BindView(R.id.ll_orderlist_twotitle)
    AutoLinearLayout llOrderlistTwotitle;
    @BindView(R.id.xrv_orderlist)
    XRecyclerView xrvOrderlist;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.iv_kong)
    ImageView ivKong;
    @BindView(R.id.rl_kong)
    AutoRelativeLayout rlKong;
    @BindView(R.id.iv_wife)
    ImageView ivWife;
    @BindView(R.id.tv_order)
    TextView tvOrder;
    @BindView(R.id.tv_tishi)
    TextView tvTishi;
    @BindView(R.id.bt_jiazai)
    Button btJiazai;
    @BindView(R.id.rl_wife)
    AutoRelativeLayout rlWife;
    @BindView(R.id.tv_order_all)
    TextView tvOrderAll;
    @BindView(R.id.ll_order_all)
    AutoLinearLayout llOrderAll;
    @BindView(R.id.tv_order_stayok)
    TextView tvOrderStayok;
    @BindView(R.id.ll_order_stayok)
    AutoLinearLayout llOrderStayok;
    @BindView(R.id.tv_order_staypay)
    TextView tvOrderStaypay;
    @BindView(R.id.ll_order_staypay)
    AutoLinearLayout llOrderStaypay;
    @BindView(R.id.tv_order_makeup)
    TextView tvOrderMakeup;
    @BindView(R.id.ll_order_makeup)
    AutoLinearLayout llOrderMakeup;
    @BindView(R.id.tv_order_sucess)
    TextView tvOrderSucess;
    @BindView(R.id.ll_order_sucess)
    AutoLinearLayout llOrderSucess;
    @BindView(R.id.tv_order_cancel)
    TextView tvOrderCancel;
    @BindView(R.id.ll_order_cancel)
    AutoLinearLayout llOrderCancel;
    @BindView(R.id.iv_orderlist)
    ImageView ivOrderlist;
    @BindView(R.id.ll_order)
    AutoLinearLayout llOrder;
    @BindView(R.id.btn_today)
    Button btnToday;
    @BindView(R.id.btn_week)
    Button btnWeek;
    @BindView(R.id.btn_month)
    Button btnMonth;
    @BindView(R.id.ll_today)
    AutoLinearLayout llToday;
    @BindView(R.id.ll_today_huixian)
    ImageView llTodayHuixian;
    @BindView(R.id.tv_time_start)
    TextView tvTimeStart;
    @BindView(R.id.ll_time_start)
    AutoRelativeLayout llTimeStart;
    @BindView(R.id.ll_strat)
    AutoLinearLayout llStrat;
    @BindView(R.id.ll_start_huixian)
    ImageView llStartHuixian;
    @BindView(R.id.tv_time_end)
    TextView tvTimeEnd;
    @BindView(R.id.ll_time_end)
    AutoRelativeLayout llTimeEnd;
    @BindView(R.id.ll_end)
    AutoLinearLayout llEnd;
    @BindView(R.id.btn_determine)
    Button btnDetermine;
    @BindView(R.id.rl_time)
    AutoRelativeLayout rlTime;
    @BindView(R.id.rotateloading)
    RotateLoading rotateloading;
    private int pageNum = 1;
    private String userId;
    private ArrayList<OrderList> totalorderLists;
    private List<OrderList> orderLists;
    private OrderListAdapter orderListAdapter;
    private String url;
    private String months;
    private String days;
    private String date;
    private int year;
    private TimePickerView pvTime;
    //标记点击事件 1，调全部 2.调需补录接口
    private String sign = "1";
    //    （0：需补录，1：已完成）
    private String type = "";
    //标记点击是开始还是结束时间（1：开始 2：结束）
    private String startOrend = "1";
    // 开始时间
    private String beginTime = "";
    //结束时间
    private String endTime = "";
    //5:待确定，10：待付款，-100待取消
    private String status = "";

    private String redsysno="";

    private Handler mhandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case 1:
                    String result = (String) msg.obj;

                    BaseModel baseModel = GsonUtil.jsonToBean(result, BaseModel.class);
                    if (baseModel.isFlag()) {
                        final OrderListModel orderListModel = GsonUtil.jsonToBean(result, OrderListModel.class);
                        OrderData orderData = orderListModel.getData();
                        orderLists = orderData.getList();
                        if (null != orderLists && orderLists.size() > 0) {
                            tvTime.setVisibility(View.VISIBLE);
                            if (pageNum == 1) {

                                totalorderLists.clear();
                                totalorderLists.addAll(orderLists);

                            } else {

                                totalorderLists.addAll(orderLists);

                            }
                        }
                        if (totalorderLists.size() <= 0) {

                            rlKong.setVisibility(View.VISIBLE);
                            rlWife.setVisibility(View.GONE);

                        } else {

                            rlKong.setVisibility(View.GONE);
                            rlWife.setVisibility(View.GONE);
                        }

                        if (null == orderListAdapter) {

                            //标记是搜索进入还是列表  1 列表 2 搜索
                            orderListAdapter = new OrderListAdapter(OrderListActivity.this, totalorderLists, "1");

                            //循环判断是否需要标红
                            for (int i = 0; i <totalorderLists.size() ; i++) {

                                if (totalorderLists.get(i).getSysno().equals(redsysno))
                                {
                                    totalorderLists.get(i).setIsred(true);
                                }
                                else
                                {
                                    totalorderLists.get(i).setIsred(false);
                                }
                            }

                            xrvOrderlist.setAdapter(orderListAdapter);

                        }

                        else {

                            //循环判断是否需要标红
                            for (int i = 0; i <totalorderLists.size() ; i++) {

                                if (totalorderLists.get(i).getSysno().equals(redsysno))
                                {
                                    totalorderLists.get(i).setIsred(true);
                                }
                                else
                                {
                                    totalorderLists.get(i).setIsred(false);
                                }

                            }

                            redsysno="";

                            orderListAdapter.notifyDataSetChanged();
                        }



                        if (pageNum == 1) {

                            tvTime.setVisibility(View.GONE);

                            xrvOrderlist.refreshComplete();

                        } else {

                            xrvOrderlist.loadMoreComplete();
                        }
                        orderListAdapter.setOnItemClickListener(new OrderListAdapter.OnItemClickListener() {
                            @Override
                            public void onClick(int position) {


//                                完成补录状态(0:需补录，1:已完成)
//                                if (!TextUtils.isEmpty(totalorderLists.get(position).getIsDitional()) && "0".equals(totalorderLists.get(position).getIsDitional())) {
//
//                                    Intent intent = new Intent(OrderListActivity.this, MakeUpInfoActivity.class);
//                                    intent.putExtra("orderlifeid", totalorderLists.get(position).getLife_so_master_id());
//                                    intent.putExtra("ordersysno", totalorderLists.get(position).getSysno());
//                                    intent.putExtra("sign", "1");
//                                    startActivityForResult(intent, 101);
//                                }
                                //待确定
                                if (BaseInfo.No_ok.equals(totalorderLists.get(position).getStatus())) {

                                    Intent intent = new Intent(OrderListActivity.this, PayCodeActivity.class);
                                    intent.putExtra("sysno", totalorderLists.get(position).getSysno());
                                    intent.putExtra("sign", "1");
                                    startActivity(intent);

                                    //待收款
                                } else if (BaseInfo.No_money.equals(totalorderLists.get(position).getStatus())) {

//                                  //如果是微信支付，跳转二维码
                                    if ("168".equals(totalorderLists.get(position).getPay_type_sysno()) || "169".equals(totalorderLists.get(position).getPay_type_sysno()) || "187".equals(totalorderLists.get(position).getPay_type_sysno())) {

                                        Intent intent = new Intent(OrderListActivity.this, PayCodeActivity.class);
                                        intent.putExtra("sysno", totalorderLists.get(position).getSysno());
                                        intent.putExtra("sign", "1");
                                        startActivity(intent);

                                    }

                                    //其他都跳转到确认收款页面
                                    else {

                                        Intent intent = new Intent(OrderListActivity.this, ConfirmActivity.class);
                                        intent.putExtra("sysno", totalorderLists.get(position).getSysno());
                                        startActivity(intent);
                                    }
                                    //待补录 已完成
                                } else if (Integer.parseInt(totalorderLists.get(position).getStatus()) >= BaseInfo.Ok_money) {
//                                     需补录
                                    if ("0".equals(totalorderLists.get(position).getIsDitional())) {

                                        Intent intent = new Intent(OrderListActivity.this, OrderSuccessActivity.class);
                                        intent.putExtra("sysno", totalorderLists.get(position).getSysno());
                                        intent.putExtra("sign", "1");
                                       startActivityForResult(intent,101);
                                    }
                                }
                            }

                            @Override
                            public void onLongClick(int position) {

                            }
                        });
                        dissmiss();

                    } else {

                        dissmiss();

                        //如果是账号被停用，就踢出到登录页面
                        if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode)) {

                            showConflictDialog(OrderListActivity.this, "账号被停用");

                        } else if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode1)) {

                            showConflictDialog(OrderListActivity.this, "您的账号在其它设备登录");

                        } else {

                            rlKong.setVisibility(View.GONE);
                            rlWife.setVisibility(View.VISIBLE);
                            Toast.makeText(OrderListActivity.this, baseModel.getErrorMsg(), Toast.LENGTH_SHORT);
                            return;

                        }

                    }

                    break;
            }
        }
    };


    @Override
    public void initView() {

        setContentView(R.layout.activity_orderlist);
        totalorderLists = new ArrayList<>();
    }

    private int month1;

    @Override
    public void initData() {


       //获取标红的订单号
        redsysno= getIntent().getStringExtra("red");
        LinearLayoutManager layoutManager = new LinearLayoutManager(OrderListActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        xrvOrderlist.setLayoutManager(layoutManager);
        xrvOrderlist.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xrvOrderlist.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        xrvOrderlist.setArrowImageView(R.mipmap.iconfont_downgrey);
        SharedPreferencesUtil.saveBoolean(this, "makeup", false);
        //获取系统日期
        Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        month1 = month + 1;

        //周日期
        if (month < 10) {

            months = "-0" + month1;

        } else {

            months = "-" + month1;
        }
        if (day < 10) {

            days = "-0" + day;

        } else {

            days = "-" + day;
        }

        //当日时间
        date = year + months + days;
        //设置默认开始结束时间
        tvTimeStart.setText(date);
        tvTimeEnd.setText(date);

        //用户id
        userId = SharedPreferencesUtil.getString(getApplicationContext(), "usersysno", "");

        tvTime.setVisibility(View.GONE);

        //时间选择器
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(2013, 1, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(year, month, day);

        //获取通知消息内容
        String url = getIntent().getStringExtra("url");
        if (!TextUtils.isEmpty(url)) {
            Toast.makeText(this, "通知消息" + url, Toast.LENGTH_SHORT).show();
        }


        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                if ("1".equals(startOrend)) {

                    tvTimeStart.setText(getTime(date));

                    beginTime = getTime(date);

                } else if ("2".equals(startOrend)) {

                    tvTimeEnd.setText(getTime(date));
                    //转换为前一天，因为不包含当天
                    endTime = DateUtils.getdate(getTime(date));
                }

            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("选择日期")//标题文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)//是否循环滚动
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .build();

        //上拉刷新
        xrvOrderlist.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {

                new Handler().postDelayed(new Runnable() {
                    public void run() {

                        tvTime.setVisibility(View.GONE);

                        pageNum = 1;
                        getData(pageNum + "", beginTime, endTime);

                    }

                }, 1000);

            }

            //加载更多
            @Override
            public void onLoadMore() {

                new Handler().postDelayed(new Runnable() {
                    public void run() {

                        pageNum += 1;
                        getData(pageNum + "", beginTime, endTime);

                    }
                }, 1000);

            }
        });

        tvTime.setVisibility(View.GONE);

        xrvOrderlist.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                View stickyInfoView = recyclerView.findChildViewUnder(
                        tvTime.getMeasuredWidth() / 2, 5);

                if (stickyInfoView != null && stickyInfoView.getContentDescription() != null) {
                    tvTime.setText(String.valueOf(stickyInfoView.getContentDescription()));
                }

                View transInfoView = recyclerView.findChildViewUnder(
                        tvTime.getMeasuredWidth() / 2, tvTime.getMeasuredHeight() + 1);

                if (transInfoView != null && transInfoView.getTag() != null) {

                    int transViewStatus = (int) transInfoView.getTag();
                    int dealtY = transInfoView.getTop() - tvTime.getMeasuredHeight();

                    if (transViewStatus == orderListAdapter.FIRST_STICKY_VIEW) {
                        tvTime.setVisibility(View.GONE);
                    } else {
                        tvTime.setVisibility(View.VISIBLE);
                    }

                    if (transViewStatus == orderListAdapter.HAS_STICKY_VIEW) {
                        if (transInfoView.getTop() > 0) {
                            tvTime.setTranslationY(dealtY);
                        } else {
                            tvTime.setTranslationY(0);
                        }
                    } else if (transViewStatus == orderListAdapter.NONE_STICKY_VIEW) {
                        tvTime.setTranslationY(0);

                    }
                }
            }
        });

        showloading();

        getData(pageNum + "", beginTime, endTime);


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        //是否刷新
        boolean isRefh = SharedPreferencesUtil.getBoolean(getApplicationContext(), "signRefresh", false);
        if (isRefh){

            setselect();
            SharedPreferencesUtil.saveBoolean(getApplicationContext(), "signRefresh", false);
        }

    }

    private boolean isall = true;
    private boolean isTime = true;

    @OnClick({R.id.ll_back, R.id.rl_orderlist_all, R.id.rl_orderlist_bulu, R.id.ll_chathome_seach, R.id.ll_chathome_saoyissao, R.id.ll_order_all, R.id.ll_order_sucess, R.id.ll_order_makeup, R.id.btn_today, R.id.btn_week,
            R.id.btn_month, R.id.ll_strat, R.id.ll_end, R.id.btn_determine, R.id.iv_orderlist, R.id.ll_order_stayok, R.id.ll_order_staypay, R.id.ll_order_cancel,R.id.bt_jiazai})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.ll_back:

                finish();

                break;
            case R.id.bt_jiazai:

                setselect();

                break;
            //点击订单头
            case R.id.rl_orderlist_all:

                if (isall) {

                    Animation animation = AnimationUtils.loadAnimation(this, R.anim.activity_open_enter);
                    llOrder.setAnimation(animation);

                    isall = false;
                    llOrder.setVisibility(View.VISIBLE);
                    xrvOrderlist.setClickable(false);
                    ivOrderlist1.setImageResource(R.mipmap.icon_pullup);
                    ivOrderlist2.setImageResource(R.mipmap.xiala);

                }

                else {

                    isall = true;
                    llOrder.setVisibility(View.GONE);
                    ivOrderlist1.setImageResource(R.mipmap.icon_pulldown);
                    ivOrderlist2.setImageResource(R.mipmap.xiala);
                    Animation animation = AnimationUtils.loadAnimation(this, R.anim.activity_close_exit);
                    llOrder.setAnimation(animation);

                }

                isTime = true;
                rlTime.setVisibility(View.GONE);
                xrvOrderlist.setVisibility(View.VISIBLE);
                tvOrderlistAll.setTextColor(getResources().getColor(R.color.pink));
                tvOrderlistBulu.setTextColor(getResources().getColor(R.color.gray));


                break;

            //点击全部订单
            case R.id.ll_order_all:

                isall = true;
                llOrder.setVisibility(View.GONE);
                ivOrderlist1.setImageResource(R.mipmap.icon_pulldown);
                tvOrderlistAll.setText("全部订单");
                status = "";
                sign = "1";
                setselect();

                break;

            //待确定
            case R.id.ll_order_stayok:

                isall = true;
                llOrder.setVisibility(View.GONE);
                ivOrderlist1.setImageResource(R.mipmap.icon_pulldown);
                tvOrderlistAll.setText("待确定");
                status = "5";
                sign = "1";
                setselect();

                break;

            //待收款
            case R.id.ll_order_staypay:

                isall = true;
                llOrder.setVisibility(View.GONE);
                ivOrderlist1.setImageResource(R.mipmap.icon_pulldown);
                tvOrderlistAll.setText("待收款");
                status = "10";
                sign = "1";
                setselect();

                break;

            //点击已完成订单
            case R.id.ll_order_sucess:

                isall = true;
                llOrder.setVisibility(View.GONE);
                ivOrderlist1.setImageResource(R.mipmap.icon_pulldown);
                tvOrderlistAll.setText("已完成");
                sign = "2";
                type = "1";
                setselect();

                break;

            //点击补录订单
            case R.id.ll_order_makeup:

                isall = true;
                llOrder.setVisibility(View.GONE);
                ivOrderlist1.setImageResource(R.mipmap.icon_pulldown);
                tvOrderlistAll.setText("需补录");
                sign = "2";
                type = "0";
                setselect();

                break;

            //已取消
            case R.id.ll_order_cancel:

                isall = true;
                llOrder.setVisibility(View.GONE);
                ivOrderlist1.setImageResource(R.mipmap.icon_pulldown);
                tvOrderlistAll.setText("已取消");
                status = "-100";
                sign = "1";
                setselect();

                break;
            //点击时间头
            case R.id.rl_orderlist_bulu:

                if (isTime) {
                    isTime = false;
                    xrvOrderlist.setVisibility(View.GONE);
                    rlTime.setVisibility(View.VISIBLE);
                    ivOrderlist1.setImageResource(R.mipmap.xiala);
                    ivOrderlist2.setImageResource(R.mipmap.icon_pullup);
                }
                else {

                    isTime = true;
                    rlTime.setVisibility(View.GONE);
                    xrvOrderlist.setVisibility(View.VISIBLE);
                    ivOrderlist1.setImageResource(R.mipmap.xiala);
                    ivOrderlist2.setImageResource(R.mipmap.icon_pulldown);

                }

                isall = true;
                llOrder.setVisibility(View.GONE);
                tvOrderlistAll.setTextColor(getResources().getColor(R.color.gray));
                tvOrderlistBulu.setTextColor(getResources().getColor(R.color.pink));

                break;
            //点击今天
            case R.id.btn_today:

                //当日时间
                cleanview();
                btnToday.setBackgroundColor(getResources().getColor(R.color.pink));
                btnToday.setTextColor(getResources().getColor(R.color.whiteblack));
                tvOrderlistBulu.setText("今日");
                //开始时间
                beginTime = year + months + days;
                //结束时间
                endTime = DateUtils.getdate(date);
                tvTimeStart.setText(beginTime);
                //当前的 年 月 日
                tvTimeEnd.setText(year + months + days);


                break;
            //点击近周
            case R.id.btn_week:

                cleanview();

                btnWeek.setBackgroundColor(getResources().getColor(R.color.pink));
                btnWeek.setTextColor(getResources().getColor(R.color.whiteblack));

                tvOrderlistBulu.setText("近7日");
                //获取今天往前一周的日期（几月几号）
                List<String> sevendate = DateUtils.getSevendate();

                try {

                    beginTime = DateUtils.getStatetime();

                } catch (ParseException e) {
                    e.printStackTrace();
                    beginTime = "";
                }
                //结束时间
                endTime = DateUtils.getdate(date);
                tvTimeStart.setText(beginTime);
                tvTimeEnd.setText(year + months + days);

                break;

            //点击近月
            case R.id.btn_month:

                cleanview();
                btnMonth.setBackgroundColor(getResources().getColor(R.color.pink));
                btnMonth.setTextColor(getResources().getColor(R.color.whiteblack));
                tvOrderlistBulu.setText("近1月");
                //开始时间
                beginTime = DateUtils.getMonth();
                //结束时间
                endTime = DateUtils.getdate(date);
                tvTimeStart.setText(beginTime);
                tvTimeEnd.setText(year + months + days);


                break;
            //点击开始时间
            case R.id.ll_strat:

                cleanview();
                startOrend = "1";
                pvTime.show();
                tvOrderlistBulu.setText("选择时间");


                break;
            //点击结束时间
            case R.id.ll_end:

                cleanview();
                startOrend = "2";
                pvTime.show();
                tvOrderlistBulu.setText("选择时间");


                break;

            //点击确定按钮
            case R.id.btn_determine:

                if (MyUtils.compare_date(tvTimeEnd.getText().toString().trim(), beginTime) != -1) {
                    isTime = true;
                    rlTime.setVisibility(View.GONE);
                    ivOrderlist2.setImageResource(R.mipmap.icon_pulldown);
                    xrvOrderlist.setVisibility(View.VISIBLE);
                    setselect();
                } else {
                    Toasty.error(getApplicationContext(), "结束日期不能大于开始日期", Toast.LENGTH_SHORT).show();
                    return;
                }


                break;

            //搜索
            case R.id.ll_chathome_seach:

                startActivity(new Intent(this, SearchActivity.class));

                break;

            case R.id.ll_chathome_saoyissao:

                if (Build.VERSION.SDK_INT >= 23) {
                    PackageManager packageManager = getPackageManager();
                    int permission = packageManager.checkPermission("android.permission.CAMERA", this.getPackageName());
                    if (PackageManager.PERMISSION_GRANTED == permission) {

                        Intent intent = new Intent(this, SaoMaActivity.class);
                        intent.putExtra("sign", "2");
                        startActivity(intent);

                    } else {
                        //没有这个权限
                        Toasty.error(getApplicationContext(), "请在应用设置界面打开本应用照相机权限", Toast.LENGTH_SHORT).show();
                    }
                }
                else {
                    if (cameraIsCanUse()) {

                        Intent intent = new Intent(this, SaoMaActivity.class);
                        intent.putExtra("sign", "2");
                        startActivity(intent);
                    }
                    else {

                        Toasty.error(getApplicationContext(), "请在应用设置界面打开本应用照相机权限", Toast.LENGTH_SHORT).show();

                    }

                }


                break;
            case R.id.iv_orderlist:

                isall = true;
                llOrder.setVisibility(View.GONE);
                ivOrderlist1.setImageResource(R.mipmap.icon_pulldown);
                Animation animation = AnimationUtils.loadAnimation(this, R.anim.activity_close_exit);
                llOrder.setAnimation(animation);

                break;
        }
    }

    //6.0以下系统判断照相机权限
    public boolean cameraIsCanUse() {
        boolean isCanUse = true;
        Camera mCamera = null;
        try {
            mCamera = Camera.open();
            Camera.Parameters mParameters = mCamera.getParameters(); //针对魅族手机
            mCamera.setParameters(mParameters);
        } catch (Exception e) {
            isCanUse = false;
        }

        if (mCamera != null) {
            try {
                mCamera.release();
            } catch (Exception e) {
                e.printStackTrace();
                return isCanUse;
            }
        }
        return isCanUse;
    }


    private void cleanview() {

        btnWeek.setBackground(getResources().getDrawable(R.drawable.button_back_order));
        btnToday.setBackground(getResources().getDrawable(R.drawable.button_back_order));
        btnMonth.setBackground(getResources().getDrawable(R.drawable.button_back_order));
        btnWeek.setTextColor(getResources().getColor(R.color.gray));
        btnToday.setTextColor(getResources().getColor(R.color.gray));
        btnMonth.setTextColor(getResources().getColor(R.color.gray));

    }

    private void setselect() {

        pageNum = 1;

        showloading();

        //隐藏空数据
        rlKong.setVisibility(View.GONE);
        rlWife.setVisibility(View.GONE);

        if (null != totalorderLists && totalorderLists.size() > 0) {
            totalorderLists.clear();
            orderLists.clear();
            //获取数据
            getData(pageNum + "", beginTime, endTime);
            orderListAdapter.notifyDataSetChanged();

        } else {

            //获取数据
            getData(pageNum + "", beginTime, endTime);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        boolean makeup = SharedPreferencesUtil.getBoolean(this, "makeup", false);

        if (requestCode == 101) {

            if (makeup) {
                //刷新页面
                setselect();
                SharedPreferencesUtil.saveBoolean(this, "makeup", false);
            }

        }
    }

    /**
     * 获取订单数据
     * userId		用户ID
     * pageNum	页码
     * pageSize
     * beginTime 开始时间
     * endTime 结束时间
     */
    private void getData(String pageNum, String beginTime, String endTime) {

        //店铺id
        String shopsysno = SharedPreferencesUtil.getString(this, "shopsysno", "");

        try {

            HashMap<String, String> sortedParams = new HashMap<String, String>();

            //全部订单
            if ("1".equals(sign)) {

                url = BaseInfo.URL + "lifeOrder/getMyLifeSalesList.do";
                sortedParams.put("pageSize", "10");
                sortedParams.put("pageNum", pageNum);

                if (!TextUtils.isEmpty(status)) {

                    sortedParams.put("status", status);
                }
                sortedParams.put("userId", userId);
                sortedParams.put("shopStoreSysno", shopsysno);

                if (!TextUtils.isEmpty(beginTime)) {

                    sortedParams.put("beginTime", beginTime);
                }
                if (!TextUtils.isEmpty(endTime)) {

                    sortedParams.put("endTime", endTime);
                }

            }
            //补录和已完成
            else if ("2".equals(sign)) {

                url = BaseInfo.URL + "lifeOrder/getDditionalRecordingList.do";
                sortedParams.put("pageSize", "10");
                sortedParams.put("pageNum", pageNum);
                sortedParams.put("type", type);
                sortedParams.put("userId", userId);
                sortedParams.put("shopStoreSysno", shopsysno);
                if (!TextUtils.isEmpty(beginTime)) {

                    sortedParams.put("beginTime", beginTime);
                }
                if (!TextUtils.isEmpty(endTime)) {
                    sortedParams.put("endTime", endTime);
                }

            }

            OkHttpUtils
                    .post()
                    .url(url)
                    .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, getApplicationContext()))
                    .build()
                    .execute(new MyStringCallback());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    class MyStringCallback extends StringCallback {
        @Override
        public void onError(Call call, Exception e, int id) {
            dissmiss();
            rlWife.setVisibility(View.VISIBLE);

        }

        @Override
        public void onResponse(String response, int id) {
            Message message = new Message();
            message.what = 1;
            message.obj = response;
            mhandler.sendMessage(message);
        }
    }

    private void dissmiss() {

        if (rotateloading.isStart()) {

            rotateloading.stop();
        }

    }

    private void showloading() {

        rotateloading = (RotateLoading) findViewById(R.id.rotateloading);

        rotateloading.start();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

}
